﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WellDone
{
    public partial class AddMenuGroupDialog : ChildWindow
    {
        public AddMenuGroupDialog()
        {
            InitializeComponent();
        }

        private async void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (btnOk.IsEnabled)
            {
                btnOk.IsEnabled = false;
                // Get the top precedence number 
                short maxPrecedence = 0;
                foreach (ServiceReferenceOpenRPOS.MenuGroup mc in Globals.db.MenuGroupRecords)
                {
                    if (mc.col_Precedence > maxPrecedence)
                        maxPrecedence = mc.col_Precedence;
                }
                if (tbMenuGroupName.Text.Trim().Length > 0)
                {
                    // Determine if a non-active record with this name already exists
                    await Globals.db.GetMenuGroupObjects("Name='" + tbMenuGroupName.Text.Trim() + "'");
                    if (Globals.db.MenuGroupRecords.Count > 0)
                    {
                        MessageBox.Show("Menu group is already exists");
                        btnOk.IsEnabled = true;
                    }
                    else
                    {
                        // Create a new menu Group with this name
                        ServiceReferenceOpenRPOS.MenuGroup mg = new ServiceReferenceOpenRPOS.MenuGroup();
                        mg.col_Name = tbMenuGroupName.Text.Trim();
                        mg.bFilterName = true;
                        mg.col_Active = true;
                        mg.bFilterActive = true;
                        mg.col_Precedence = (short)(maxPrecedence + 1);
                        mg.bFilterPrecedence = true;
                        mg.col_Visible = (cbMenuGroupVisible.IsChecked == true);
                        mg.bFilterVisible = true;
                        await Globals.db.AddMenuGroupObject(mg);
                        Globals.menuItems.initMenuGroups(true);
                        this.DialogResult = true;
                    }
                }
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void tbMenuGroupName_KeyDown(object sender, KeyEventArgs e)
        {
            // Call the OK button handlers if "Enter" is pressed
            if (e.Key == Key.Enter)
                OKButton_Click(sender, e);
        }
    }
}

